package com.code.demo.mvp.base;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.code.demo.ui.common.DialogLoading;
import com.code.demo.ui.common.ToastFactory;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by yangliguo on 2019/3/1.
 */

public abstract class BaseMvpActivity<T extends IPresenter> extends Activity implements IView{

    protected T presenter;

    public abstract T createPresenter();

    public abstract int getLayoutResId(Bundle savedInstanceState);

    public abstract void initViews(Bundle savedInstanceState);

    private DialogLoading loading = null;

    private Unbinder unbinder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(getLayoutResId(savedInstanceState));

        unbinder = ButterKnife.bind(this);

        presenter = createPresenter();
        if (presenter != null) {
            presenter.attachView(this);
        }

        initViews(savedInstanceState);
    }

    @Override
    protected void onDestroy() {

        unbinder.unbind();

        if (loading != null) {
            loading.dismiss();
        }
        loading = null;

        if (presenter != null) {
            presenter.onDestroy();
        }
        presenter = null;

        super.onDestroy();
    }

    @Override
    public void showError(String msg) {
        ToastFactory.showToast(this, msg);
    }

    @Override
    public void handleException(Exception e) {
        e.printStackTrace();
        hideLoading();
        showError(e.getMessage());
    }

    @Override
    public void showLoading() {
        if (loading == null) {
            loading = new DialogLoading(this, "请稍候");
            loading.show();
        }
    }

    @Override
    public void hideLoading() {
        if (loading != null) {
            loading.dismiss();
        }
    }
}
